package se.hrbustrc.hlgshopping.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import se.hrbustrc.hlgshopping.entity.PCTreeNode;
import se.hrbustrc.hlgshopping.entity.PCategory;
import se.hrbustrc.hlgshopping.mapper.PCategoryMapper;
import se.hrbustrc.hlgshopping.service.PCategoryService;
import se.hrbustrc.hlgshopping.utils.SQLCommService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PCategoryServiceImpl implements PCategoryService {
    @Autowired
    private PCategoryMapper pCategoryMapper;
    @Autowired
    SQLCommService sqlCommService;

    @Override
    public void addPCategory(PCategory pCategory) {
        pCategoryMapper.insert(pCategory);
    }

    @Override
    public void editPCategory(PCategory pCategory) {
        pCategoryMapper.updateById(pCategory);
    }

    @Override
    public void deletePCategory(Integer pCategoryId) {
        pCategoryMapper.deleteById(pCategoryId);
    }

    @Override
    public PCategory getPCategoryById(int pCategoryId) {
        return pCategoryMapper.selectById(pCategoryId);
    }

    @Override
    public List<PCTreeNode> getPCTreeList(Integer pid) {
        List<PCTreeNode> result=new ArrayList<>();

        PCTreeNode node=getNodeAndChildren(pid);
        result.add(node);

        return result;

    }
    @Override
    public PCTreeNode getNodeAndChildren(int pcId){
        PCTreeNode result=new PCTreeNode();
        String strSQL=String.format("select FPCateName from tb_pcategory where FPCatId=%s",pcId);
        String strCateName=sqlCommService.getFieldStr(strSQL);
        result.setCateId(pcId);
        result.setCateName(strCateName);
        List<PCTreeNode> children=new ArrayList<>();
        strSQL=String.format("select count(*) from tb_pcategory where FParentId=%s",pcId);
        if(strSQL.equals("")||strSQL.equals("0")){
            children=null;
        }else{
            strSQL=String.format("select FPCatId from tb_pcategory where FParentId=%s",pcId);
            List<Map<String,Object>> chirldrenList=sqlCommService.listResult(strSQL);
            for(int i=0;i<chirldrenList.size();i++){
                Map<String,Object> child=chirldrenList.get(i);
                int pcIdChild=Integer.parseInt(child.get("FPCatId").toString());
                PCTreeNode childNode=getNodeAndChildren(pcIdChild);
                if(childNode!=null){
                    System.out.println("下级："+childNode.getCateName());
                    children.add(childNode);
                }
            }
            if(children.size()>0){
                result.setChildren(children);
            }
        }
        return result;
    }
    // 在 PCategoryServiceImpl 实现类中添加以下方法实现
    @Override
    public PCTreeNode getParentCategoryById(int pcId) {
        // 1. 找到当前分类
        PCategory currentCategory = this.getPCategoryById(pcId);
        if (currentCategory == null) {
            return null; // 分类不存在
        }

        // 2. 不断向上追溯，直到 parentId = 0
        int rootId = currentCategory.getpCategoryParentId();
        while (rootId > 0) {
            PCategory parent = this.getPCategoryById(rootId);
            if (parent == null) {
                break; // 找不到上级，跳出
            }
            rootId = parent.getpCategoryParentId();
            if (rootId == 0) {
                // 最顶级父分类就是 parent
                rootId = parent.getpCategoryId();
                break;
            }
        }

        // 3. 如果本身就是根节点
        if (currentCategory.getpCategoryParentId() == 0) {
            rootId = currentCategory.getpCategoryId();
        }

        // 4. 从根节点开始构建整棵树
        return getNodeAndChildren(rootId);
    }
    @Override
    public PCTreeNode getParentChainById(int pcId) {
        // 1. 找到当前分类
        PCategory current = this.getPCategoryById(pcId);
        if (current == null) {
            return null;
        }

        // 2. 构建当前节点
        PCTreeNode node = new PCTreeNode();
        node.setCateId(current.getpCategoryId());
        node.setCateName(current.getpCategoryName());
        node.setParentId(current.getpCategoryParentId());

        // 3. 如果有父级，递归往上包裹
        if (current.getpCategoryParentId() > 0) {
            PCTreeNode parentNode = getParentChainById(current.getpCategoryParentId());
            if (parentNode != null) {
                List<PCTreeNode> children = new ArrayList<>();
                children.add(node);   // 只保留当前这个子节点
                parentNode.setChildren(children);
                return parentNode;
            }
        }

        // 4. 如果是根节点，直接返回自己
        return node;
    }
    
    @Override
    public List<Integer> getAllCategoryIdsById(int categoryId) {
        List<Integer> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);
        
        // 递归获取所有子分类ID
        getAllChildCategoryIds(categoryId, categoryIds);
        
        return categoryIds;
    }
    
    /**
     * 递归获取所有子分类ID
     * @param parentId 父分类ID
     * @param categoryIds 分类ID列表
     */
    private void getAllChildCategoryIds(int parentId, List<Integer> categoryIds) {
        // 查询直接子分类
        String strSQL = String.format("select FPCatId from tb_pcategory where FParentId=%s", parentId);
        List<Map<String, Object>> childrenList = sqlCommService.listResult(strSQL);
        
        for (Map<String, Object> child : childrenList) {
            int childId = Integer.parseInt(child.get("FPCatId").toString());
            categoryIds.add(childId);
            // 递归获取子分类的子分类
            getAllChildCategoryIds(childId, categoryIds);
        }
    }
}
